//
//  MIDIfoundController.m
//  迷笛
//
//  Created by . on 2018/9/16.
//  Copyright © 2018年 🍃🌺🌺🍃. All rights reserved.
//

#import "MIDIfoundController.h"
#import "MIDIdatumCell.h"
#import "CustomTextField.h"
#import "MIDIfoundCell.h"

#import <QiniuSDK.h>

@interface MIDIfoundController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UIScrollView * scrollView;
@property(nonatomic,strong)UIView * headLabel;
@property(nonatomic,strong)UIButton * addHeard;
@property(nonatomic,strong)UITextField * nameTextfied;
@property(nonatomic,strong)UIView * textview;
@property(nonatomic,strong)UIView * typeLable;
@property(nonatomic,strong)UILabel * typetext;
@property(nonatomic,strong)UIButton * typeBtn;
@property(nonatomic,strong)UITextView *textField;

@property(nonatomic,strong)UIButton * hand;
@property(nonatomic,strong)UIImagePickerController * _imagePicker;
@property(nonatomic,strong)UIImageView * MYImage;

@property(nonatomic,strong)UIView * chooseView;
@property(nonatomic,strong)UITableView * chooseTable;
@property(nonatomic,copy)NSArray * choosrArr;
@property(nonatomic,strong)UIImageView* image;
@property(nonatomic,copy)NSNumber *typeNumber;
@property(nonatomic,copy)NSString * foundToken;
@property(nonatomic,copy)NSString * qinniuToken;

@property(nonatomic,copy)NSString *circleApi;


@property(nonatomic,copy)NSString *qiniuHash;
@property(nonatomic,copy)NSString *apptoken;

@end

@implementation MIDIfoundController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    self.apptoken = [user objectForKey:@"APPToken"];

    _choosrArr = @[@"音乐人",@"演出现场",@"粉圈",@"跳蚤市场"];
    [self Table];
    [self qiniuToken];
    self.view.backgroundColor =[UIColor blackColor];
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(Block:)];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    [self.navigationItem.leftBarButtonItem setImage:[[UIImage imageNamed:@"后退"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.scrollView.backgroundColor =[UIColor blackColor];
    [self.view addSubview:self.scrollView];

    [self scrollUI];
    [self HomeUI];
    
    
}
#pragma mark - 获取七牛Token

-(void)qiniuToken
{
    NSString * foundtoken = @"token";
    _foundToken = [NSString stringWithFormat:@"%@%@",MIDIApiRoot,foundtoken];

    [EdHttp get:_foundToken params:nil progress:^(id downloadProgress)
     {
         
     }
        success:^(id responseObject)
     {
         NSLog(@"七牛token%@",responseObject);
         self.qinniuToken = [responseObject objectForKey:@"data"];
         NSLog(@"qinniuToken---%@",self.qinniuToken);
     }
        failure:^(NSError *error)
     {
         NSLog(@"失败");
     }];
}
#pragma mark - 图片上传七牛服务器
-(void)qiniuRequest
{
    NSString *token =self.qinniuToken;
//    NSString *tokendata =[token stringByRemovingPercentEncoding];

    NSString * Key = @"BTULw0loify0c2Wm6n501oiqz8XZzdiCKl05Aiab";
//    NSString *keydata = [key stringByRemovingPercentEncoding];

//    NSString * mimeType = @"image/jpeg";
    
    QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:@"image/jpeg" progressHandler:nil params:@{ @"x:mimeType":@"fooval" } checkCrc:YES cancellationSignal:nil];

    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    NSData *Data = UIImageJPEGRepresentation(self.MYImage.image, 0.5f);
    
    [upManager putData:Data key:nil token:token
    complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp)
     {
        NSLog(@"info--%@", info);
        NSLog(@"resp--%@", resp);
        NSLog(@"key--%@", Key);
        self.qiniuHash = [NSString stringWithFormat:@"/%@",[resp objectForKey:@"key"]];

         NSLog(@"值--%@", self.qiniuHash);
         
         [self createRequest];

    }
    option:opt];
}
#pragma mark -
-(void)createRequest
{
    
    NSLog(@"文字:%@,值%@,内容 %@,圈子id %@,token%@",self.nameTextfied.text,self.qiniuHash,self.textField.text,self.typeNumber,self.apptoken);
    
    NSDictionary * createdic = @{@"name":self.nameTextfied.text,@"cover":self.qiniuHash,@"intro":self.textField.text,@"category_id":self.typeNumber,@"token":self.apptoken};
    
    NSString * circle = @"circle/create";
    _circleApi = [NSString stringWithFormat:@"%@%@",MIDIApiRoot,circle];
    NSLog(@"发布圈子%@",_circleApi);
    [EdHttp post:_circleApi params:createdic progress:^(id uploadProgress)
     {
         
     }
         success:^(id responseObject)
     {
         NSLog(@"创建圈子真按钮%@",responseObject);
         if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
         {
             [SVProgressHUD showSuccessWithStatus:@"创建成功"];
             [SVProgressHUD dismissWithDelay:1.0];
             [self.navigationController popViewControllerAnimated:YES];
         }
         else
         {
             [SVProgressHUD showErrorWithStatus:@"创建失败"];
             [SVProgressHUD dismissWithDelay:1.0];

         }

     }
         failure:^(NSError *error)
     {
         NSLog(@"失败");
     }];
}

-(void)Handfond:(UIButton * )sender
{
    [self qiniuRequest];
    

}
-(void)Table
{
    if (!_chooseTable)
    {
        _chooseTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 334) style:UITableViewStyleGrouped];
        _chooseTable.delegate =self;
        _chooseTable.dataSource = self;
        _chooseTable.backgroundColor = [UIColor colorWithHexString:@"#FFFFFF"];

        [self.chooseView addSubview:self.chooseTable];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return _choosrArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString * cellID = @"cell";
    UITableViewCell  * cell =[tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }
    cell.textLabel.text = _choosrArr[indexPath.row];
//    cell.chooseImage.image = [UIImage imageNamed:@"gougou"];

   
    
    return cell;
}
-(UIView *)chooseView
{
    if (!_chooseView)
    {
        _chooseView =[[UIView alloc]initWithFrame:CGRectMake(0, 700, self.view.frame.size.width, 334)];
        _chooseView.backgroundColor =[UIColor whiteColor];
    }
    return _chooseView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.row == 0)
    {
        [_typeBtn setTitle:@"音乐人" forState:0];
        self.typeNumber = [NSNumber numberWithInt:1];
        
        NSLog(@"类型%@",self.typeNumber);
    }
    if (indexPath.row == 1)
    {
        [_typeBtn setTitle:@"演出现场" forState:0];
        self.typeNumber = [NSNumber numberWithInt:2];
        NSLog(@"类型%@",self.typeNumber);

    }
    if (indexPath.row == 2)
    {
        [_typeBtn setTitle:@"粉圈" forState:0];
        self.typeNumber = [NSNumber numberWithInt:3];
        NSLog(@"类型%@",self.typeNumber);

    }
    if (indexPath.row == 3)
    {
        [_typeBtn setTitle:@"跳蚤市场" forState:0];
        self.typeNumber = [NSNumber numberWithInt:4];
        NSLog(@"类型%@",self.typeNumber);
    }

    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = self.chooseView.frame;
        frame.origin.y = 700.f;
        [self.chooseView setFrame:frame];
        [self.view addSubview:self.chooseView];
    }];
    
    NSLog(@"调试%@",self.typeNumber);

}
#pragma mark - scrollUI
-(void)scrollUI
{
    [self.scrollView addSubview:self.headLabel];
    [self.headLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(WidthScale(50));
        make.centerX.equalTo(self.scrollView);
        make.width.mas_offset(WidthScale(90));
        make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(90):HeightScale(90));
    }];
    [self.headLabel addSubview:self.MYImage];
    
    [self.MYImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.headLabel);
        make.centerY.equalTo(self.headLabel);
        make.width.mas_offset(WidthScale(90));
        make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(90):HeightScale(90));
    }];
    
    [self.headLabel addSubview:self.addHeard];
    [self.addHeard mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.headLabel);
        make.centerY.equalTo(self.headLabel);
        make.width.mas_offset(WidthScale(70));
        make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(70):HeightScale(70));
    }];
    [self.scrollView addSubview:self.nameTextfied];
    [self.nameTextfied mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headLabel.mas_bottom).mas_offset(WidthScale(20));
        make.left.mas_offset(0);
        make.width.mas_offset(WidthScale(self.view.frame.size.width));
        make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(50):HeightScale(50));
    }];
    [self.scrollView addSubview:self.textField];
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameTextfied.mas_bottom).mas_offset(WidthScale(20));
        make.left.equalTo(self.nameTextfied);
        make.width.mas_offset(WidthScale(self.view.frame.size.width));
        make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(200):HeightScale(200));
    }];


    
    [self.scrollView addSubview:self.typeLable];
    [self.typeLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textField.mas_bottom).mas_offset(WidthScale(20));
        if (make.top.equalTo(self.textField.mas_bottom).mas_offset(WidthScale(200)))
        {
            self.scrollView.contentSize = CGSizeMake(0, self.view.frame.size.height+200);
        }
        make.left.equalTo(self.nameTextfied);
        make.width.mas_offset(WidthScale(self.view.frame.size.width));
        make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(100):HeightScale(100));
    }];
    [self.typeLable addSubview:self.typetext];
    [self.typetext mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.typeLable).mas_offset(WidthScale(10));
        make.left.equalTo(self.typeLable).mas_offset(WidthScale(10));
    }];
    [self.typeLable setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    
    [self.typeLable addSubview:self.typeBtn];
    [self.typeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.typetext.mas_bottom).mas_offset(WidthScale(10));
        make.left.equalTo(self.typetext);
        make.width.mas_offset(WidthScale(103));
        make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(29):HeightScale(29));
        
    }];

}
-(UIView *)headLabel
{
    if (!_headLabel)
    {
        _headLabel =[[UIView alloc]init];
        _headLabel.backgroundColor =[UIColor colorWithHexString:@"#1B212F"];
    }
    return _headLabel;
}
-(UIImageView *)MYImage
{
    if (!_MYImage)
    {
        _MYImage =[[UIImageView alloc]init];
        _MYImage.image = [UIImage imageNamed:@""];
    }
    return _MYImage;
}
-(UIButton *)addHeard
{
    if (!_addHeard)
    {
        _addHeard =[[UIButton alloc]init];
        [_addHeard setBackgroundImage:[UIImage imageNamed:@"quanzi-jiahao"] forState:0];
        [_addHeard addTarget:self action:@selector(addheardBtn:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _addHeard;
}
-(void)addheardBtn:(UIButton * )sender
{
    [self choose];
    [_addHeard setBackgroundImage:[UIImage imageNamed:@""] forState:0];
}
#pragma mark - 选择图片
-(void)choose
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：从相册选择，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
        {
            //初始化UIImagePickerController
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
            //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
            //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
            PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //允许编辑，即放大裁剪
            PickerImage.allowsEditing = YES;
            //自代理
            PickerImage.delegate = self;
            //页面跳转
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
    //按钮：拍照，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
        {
            //其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            //获取方式:通过相机
            PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            PickerImage.allowsEditing = YES;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    //定义一个newPhoto，用来存放我们选择的图片。
    
    UIImage * newPhoto = [info objectForKey:UIImagePickerControllerEditedImage];
    
    self.MYImage.image = newPhoto;
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(UITextField *)nameTextfied
{
    if (!_nameTextfied)
    {
        _nameTextfied =[[UITextField alloc]init];
//        _nameTextfied.borderStyle = UITextBorderStyleBezel;
        _nameTextfied.backgroundColor =[UIColor colorWithHexString:@"#1B212F"];
        _nameTextfied.placeholder = @"请输入";
        _nameTextfied.textColor = [UIColor whiteColor];
        [self.nameTextfied setValue:[UIColor whiteColor]  forKeyPath:@"_placeholderLabel.textColor"];
        [self.nameTextfied setValue:[UIFont systemFontOfSize:15.0] forKeyPath:@"_placeholderLabel.font"];
    }
    return _nameTextfied;
}
-(UITextView *)textField
{
    if (!_textField)
    {
        _textField =[[UITextView alloc]init];
        _textField.font =[UIFont systemFontOfSize:WidthScale(15)];
        _textField.backgroundColor =[UIColor colorWithHexString:@"#1B212F"];
        _textField.textColor = [UIColor whiteColor];
    }
    return _textField;
}
-(UIView *)typeLable
{
    if (!_typeLable)
    {
        _typeLable =[[UIView alloc]init];
        _typeLable.backgroundColor =[UIColor colorWithHexString:@"#1B212F"];
    }
    return _typeLable;
}
-(UILabel *)typetext
{
    if (!_typetext)
    {
        _typetext =[[UILabel alloc]init];
        _typetext.text = @"选择圈子类别（必选）";
        _typetext.textColor = [UIColor colorWithHexString:@"#999999"];
        _typetext.font =[UIFont systemFontOfSize:WidthScale(14)];
    }
    return _typetext;
}
-(UIButton *)typeBtn
{
    if (!_typeBtn)
    {
        _typeBtn =[[UIButton alloc]init];
        [_typeBtn setTitle:@"音乐人" forState:0];
        [_typeBtn setBackgroundColor:[UIColor colorWithHexString:@"#999999"]];
        _typeBtn.titleLabel.font = [UIFont systemFontOfSize:WidthScale(15)];
        _typeBtn.layer.masksToBounds = YES;
        [_typeBtn.layer setCornerRadius:WidthScale(15)]; //设置矩圆角半径
        [_typeBtn addTarget:self action:@selector(typeBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _typeBtn;
}

-(void)typeBtn:(UIButton * )sender
{
    [UIView animateWithDuration:1 animations:^{
        CGRect frame = self.chooseView.frame;
        frame.origin.y = 270;
        [self.chooseView setFrame:frame];
        [self.view addSubview:self.chooseView];
    }];
}
    // 返回上一级
-(void)Block:(UIButton * )sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = NO;//Bar的模糊效果，默认为YES
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:@"#171717"];
    self.title = @"创建圈子";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFFFFF"],NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:WidthScale(17)]}];
    //    去掉导航黑线
    UIImage *img = [UIImage imageNamed:@""];
    [self.navigationController.navigationBar setBackgroundImage:img  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
}
-(void)HomeUI
{

    [self.view addSubview:self.hand];
    [self.hand mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_offset(kDevice_Is_iPhoneX?WidthScale(-40):WidthScale(0));
            make.centerX.equalTo(self.view);
            make.width.mas_offset(self.view.frame.size.width);
        make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(49):HeightScale(49));
    }];
}

-(UIButton *)hand
{
    if (!_hand)
    {
        _hand =[[UIButton alloc]init];
        [_hand setBackgroundColor:[UIColor colorWithHexString:@"#FF005D"]];
        [_hand setTitle:@"创建圈子" forState:0];
        [_hand addTarget:self action:@selector(Handfond:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _hand;
}
@end
